using System;
using System.Collections.Generic;
using System.Text;
using Mpi.Common;
using Mpi.Common.Collections;
using System.ComponentModel;


namespace Xeml.Document
{
    /// <summary>
    /// Represents a story split.
    /// </summary>
    public class StorySplit : StoryBase, ITimeObject
    {
        #region Fields
           private TimeSpan _timePoint; 
        #endregion

        #region Properties
              /// <summary>
        /// The relative time point of the split.
        /// </summary>
        public TimeSpan TimePoint
        {
            get
            {
                return this._timePoint;
            }
            set
            {
                TimeSpan old = this._timePoint;
                if (this._timePoint != value)
                {
                    MoveValues(old, value);
                    this._timePoint = value;
                    
                    OnTimePointChanged(old, this._timePoint);
                    OnPropertyChanged("Time");
                }
            }
        }

        private void MoveValues(TimeSpan oldVal, TimeSpan newVal)
        {
            foreach (DynamicTerm p in this._variables)
            {
                List<DynamicValueBase> toRemove = new List<DynamicValueBase>();
                foreach (DynamicValueBase vb in p.Values)
                {
                    if (vb.Time == oldVal)
                        vb.Time = newVal;
                    else if (vb.Time < newVal)
                        toRemove.Add(vb);
                }
                foreach (DynamicValueBase vb in toRemove)
                {
                    p.Values.Remove(vb);
                }
            }
        } 
        #endregion

        #region Methods

        /// <summary>
        /// Creats a string representation of this object.
        /// </summary>
        /// <returns>The string representation.</returns>
        public override string ToString()
        {
            return _label + "@" + this._timePoint.ToString();
        }

        #endregion

        public event EventHandler<PropertyHasChangedEventArgs<TimeSpan>> TimePointHasChanged;

        protected virtual void OnTimePointChanged(TimeSpan oldVal, TimeSpan newVal)
        {
            if (TimePointHasChanged != null)
                TimePointHasChanged(this, new PropertyHasChangedEventArgs<TimeSpan>(oldVal,newVal));
         }


        #region INotifyPropertyChanged Members

        //public event PropertyChangedEventHandler PropertyChanged;
        //protected virtual void OnPropertyChanged(string prop)
        //{
        //    if (PropertyChanged != null)
        //        PropertyChanged(this, new PropertyChangedEventArgs(prop));
        //}

        #endregion

       
    }
}
